/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: SemaphoreTest
 * Author:   zengjian
 * Date:     2018/8/7 9:18
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package fun.codedesign.jdk.thread;

import java.util.concurrent.Semaphore;

/**
 * 〈用来做流控〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/8/7 9:18
 */
public class SemaphoreTest {

    public static void main(String[] args) {
        final Semaphore semaphore = new Semaphore(5);

        for (int i = 0; i < 10; i++) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        System.out.println(Thread.currentThread().getName() + "获取锁前");
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + "获得锁");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                    } finally {
                        //semaphore.release();
                        //System.out.println(Thread.currentThread().getName()+"释放锁");
                    }
                }
            }.start();
        }

        while (true) {
            long now1 = System.currentTimeMillis();
            while (true) {
                // System.out.println("进入循环块");
                long now2 = System.currentTimeMillis();
                long distance = now2 - now1;
                // System.out.println(distance);
                if (distance > 1000) {
                    semaphore.release(20);
                    System.out.println("令牌数:" + semaphore.availablePermits());
                    break;
                }
            }
        }
//        try {
//            Thread.currentThread().join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}